<template>
	<div class="layout-padding-auto layout-padding-view" v-loading="loading">
		<el-form ref="formRef" :model="form" label-width="140px" :rules="rules" status-icon>
			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>基本信息</span>
					</div>
				</template>
				<el-form-item label="商品名称" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="商品子标题" prop="subTitle">
					<el-input v-model="form.subTitle" maxlength="50" type="textarea" show-word-limit :rows="2"></el-input>
				</el-form-item>
				<el-form-item label="商品图" prop="spuUrls">
					<SelectMaterial v-model="form.spuUrls" :canChooseImagesNum="5"></SelectMaterial>
				</el-form-item>
				<el-form-item label="商品类目" prop="categoryIds">
					<el-cascader :options="categoryTreeList" v-model="form.categoryIds" clearable :props="defaultProps"
						@change="changeCategory"></el-cascader>
				</el-form-item>
				<el-form-item label="运费模板" prop="freightTemplateId">
					<el-select v-model="form.freightTemplateId" clearable>
						<el-option v-for="(item, index) in freightTemplateList" :key="index" :label="item.name"
							:value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品状态" prop="status">
					<el-radio-group v-model="form.status">
						<el-radio label="0">下架</el-radio>
						<el-radio label="1">上架</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="商品销量" prop="salesVolume">
					<el-input-number style="width: 100%" v-model="form.salesVolume" :min="0" :precision="0"
						controls-position="right" />
				</el-form-item>
			</el-card>
			<el-card class="box-card">
				<!-- 多规格 -->
				<el-form-item label="多规格" prop="enableSpecs">
					<el-switch v-model="form.enableSpecs" inline-prompt active-value="1" inactive-value="0" active-text="是"
						inactive-text="否" @change="changeEnableSpecs"></el-switch>
				</el-form-item>
				<el-form-item label="多规格" v-if="form.enableSpecs == '1'">
					<div style="width: 100%">
						<Sku :specsList="specsList" :skusData="form.goodsSkus" :goodsSpuSpecs="goodsSpuSpecs"
							@getGoodsSkus="getGoodsSkus"></Sku>
					</div>
				</el-form-item>
				<el-row v-if="form.enableSpecs == '0'">
					<el-col :span="12">
						<el-form-item label="商品原价（元）" prop="sku.originalPrice">
							<el-input-number v-model="form.sku.originalPrice" :min="0.01" :precision="2"
								controls-position="right" />
						</el-form-item>
						<el-form-item label="商品成本价（元）" prop="sku.costPrice">
							<el-input-number v-model="form.sku.costPrice" :min="0.01" :precision="2"
								controls-position="right" />
						</el-form-item>
						<el-form-item label="一级分销比例" prop="sku.firstRate">
							<el-input-number v-model="form.sku.firstRate" :min="0" :precision="0"
								controls-position="right" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="商品售价（元）" prop="sku.salesPrice">
							<el-input-number v-model="form.sku.salesPrice" :min="0.01" :precision="2"
								controls-position="right" />
						</el-form-item>
						<el-form-item label="商品库存" prop="sku.stock">
							<el-input-number v-model="form.sku.stock" :min="0" :precision="0" controls-position="right" />
						</el-form-item>
						<el-form-item label="二级分销比例" prop="sku.secondRate">
							<el-input-number v-model="form.sku.secondRate" :min="0" :precision="0"
								controls-position="right" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>
			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>商品详情</span>
					</div>
				</template>
				<el-form-item label="商品描述" prop="description">
					<Editor v-model:get-html="form.description" height="500px" :disable="false"></Editor>
				</el-form-item>
			</el-card>
			<div class="goods-footer">
				<div class="button">
					<el-button @click="handleClose">关 闭</el-button>
					<el-button type="primary" :disabled="loading" @click="submitForm(formRef)"> 确 认 </el-button>
				</div>
			</div>
		</el-form>
	</div>
</template>
<script lang="ts">
import { defineComponent, defineAsyncComponent, ref, reactive, toRefs } from 'vue';
import { addObj, editObj, getById } from '/@/api/mall/goodsspu';
import { getList as getFreightTemplateList } from '/@/api/mall/freighttemplate';
import { getPage as getCategoryTree } from '/@/api/mall/goodscategory';
import { getList as getSpecsList } from '/@/api/mall/goodsspecs';
import { getList as getGoodsSpuSpecs } from '/@/api/mall/goodsspuspecs';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, FormInstance } from 'element-plus';
interface DataState {
	form: {
		id: undefined;
		name: string;
		subTitle: string;
		spuUrls: Array<string>;
		salesVolume: number;
		enableSpecs: string;
		freightTemplateId: string;
		status: string;
		description: string;
		goodsSkus: Array<any>;
		goodsSpuSpecs: Array<any>;
		categoryFirstId: string;
		categorySecondId: string;
		sku: {
			originalPrice: number;
			costPrice: number;
			firstRate: number;
			salesPrice: number;
			stock: number;
			secondRate: number;
		};
		categoryIds: Array<string>;
	};
	rules: any;
	freightTemplateList: Array<any>;
	categoryTreeList: Array<any>;
	specsList: Array<any>;
	goodsSpuSpecs: Array<any>;
}
export default defineComponent({
	components: {
		Editor: defineAsyncComponent(() => import('/@/components/editor/index.vue')),
		SelectMaterial: defineAsyncComponent(() => import('/@/components/selectMaterial/index.vue')),
		Sku: defineAsyncComponent(() => import('/@/components/sku/index.vue')),
	},
	emits: ['initPage'],
	setup(props, ctx) {
		const data = reactive<DataState>({
			form: {
				id: undefined,
				name: '',
				subTitle: '',
				spuUrls: [],
				salesVolume: 0,
				enableSpecs: '0',
				freightTemplateId: '',
				status: '1',
				description: '',
				goodsSkus: [],
				goodsSpuSpecs: [],
				categoryFirstId: '',
				categorySecondId: '',
				sku: {
					originalPrice: 0,
					costPrice: 0,
					salesPrice: 0,
					stock: 0,
					secondRate: 0,
					firstRate: 0,
				},
				categoryIds: [],
			},
			rules: {
				name: [
					{
						required: true,
						message: '请输入商品名称',
						trigger: 'change',
					},
				],
				spuUrls: [
					{
						required: true,
						message: '请上传商品图',
						trigger: 'change',
					},
				],
				status: [
					{
						required: true,
						message: '请选择商品状态',
						trigger: 'change',
					},
				],
				freightTemplateId: [
					{
						required: true,
						message: '请选择运费模板',
						trigger: 'change',
					},
				],
				categoryIds: [
					{
						required: true,
						message: '请选择商品类目',
						trigger: 'change',
					},
				],
				description: [
					{
						required: true,
						message: '请输入商品描述',
						trigger: 'change',
					},
				],
				'sku.originalPrice': [
					{
						required: true,
						message: '请输入商品原价（元）',
						trigger: 'change',
					},
				],
				'sku.salesPrice': [
					{
						required: true,
						message: '请输入商品销售价（元）',
						trigger: 'change',
					},
				],
				'sku.costPrice': [
					{
						required: true,
						message: '请输入商品成本价（元）',
						trigger: 'change',
					},
				],
				'sku.stock': [
					{
						required: true,
						message: '请输入商品库存数量',
						trigger: 'change',
					},
				],
			},
			freightTemplateList: [],
			categoryTreeList: [],
			specsList: [],
			goodsSpuSpecs: [],
		});
		const $route = useRouter();
		const $useRoute = useRoute();
		const loading = ref(false);
		const formRef = ref();
		const wangEditorRef = ref();
		const defaultProps = {
			label: 'name',
			value: 'id',
			children: 'children',
		};
		const fullscreen = ref(false);
		/**
		 * 关闭事件
		 */
		const handleClose = () => {
			resetForm(formRef.value);
			$route.back();
		};
		/**
		 * 重置表单
		 */
		const resetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			data.form = {
				id: undefined,
				name: '',
				subTitle: '',
				spuUrls: [],
				salesVolume: 0,
				enableSpecs: '0',
				freightTemplateId: '',
				status: '1',
				description: '',
				goodsSkus: [],
				goodsSpuSpecs: [],
				categoryFirstId: '',
				categorySecondId: '',
				sku: {
					originalPrice: 0,
					costPrice: 0,
					salesPrice: 0,
					stock: 0,
					secondRate: 0,
					firstRate: 0,
				},
				categoryIds: [],
			};
			loading.value = false;
			// formEl.resetFields();
		};
		/**
		 * 提交按钮
		 */
		const submitForm = async (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					// 单规格sku 处理
					if (data.form.enableSpecs == '0') {
						data.form.goodsSkus = [data.form.sku];
					}
					// 多规格sku 处理
					if (data.form.enableSpecs == '1') {
						if (data.form.goodsSpuSpecs && data.form.goodsSpuSpecs.length > 0) {
							data.form.goodsSpuSpecs[0].goodsSkuSpecsValues.forEach((item: any) => {
								item.picUrl = item.picUrls ? item.picUrls[0] : '';
							});
						}
					}
					loading.value = true;
					if (data.form.id) {
						//修改
						edit();
					} else {
						//新增
						add();
					}
				}
			});
		};
		/**
		 * 新增
		 */
		const add = () => {
			addObj(data.form)
				.then((response) => {
					ElMessageBox.confirm('新增成功', '提示', {
						confirmButtonText: '继续添加',
						cancelButtonText: '返回列表',
						type: 'success',
					})
						.then(() => {
							resetForm(formRef.value);
						})
						.catch(() => {
							handleClose();
						});
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 修改
		 */
		const edit = () => {
			editObj(data.form)
				.then((response) => {
					ElMessageBox.confirm('修改成功', '提示', {
						confirmButtonText: '新增商品',
						cancelButtonText: '返回列表',
						type: 'success',
					})
						.then(() => {
							resetForm(formRef.value);
						})
						.catch(() => {
							handleClose();
						});
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 查询全部运费模板
		 */
		const getFreightTemplate = () => {
			getFreightTemplateList({}).then((response) => {
				data.freightTemplateList = response.data.data;
			});
		};
		/**
		 * 查询全部商品类目
		 */
		const getCategory = () => {
			getCategoryTree().then((response) => {
				data.categoryTreeList = response.data.data;
			});
		};

		/**
		 * 商品类目改变事件
		 */
		const changeCategory = (categoryIds: any) => {
			data.form.categoryFirstId = categoryIds[0];
			data.form.categorySecondId = categoryIds[1];
		};
		/**
		 * 查询规格数据
		 */
		const getSpecs = () => {
			getSpecsList({}).then((response) => {
				data.specsList = response.data.data;
			});
		};
		/**
		 * 多规格change事件 1.开始多规格；0.关闭多规格
		 */
		const changeEnableSpecs = (status: string) => {
			if (status == '1') {
				getSpecs();
			} else {
				if (!data.form.sku) {
					data.form.sku = {
						originalPrice: 0,
						costPrice: 0,
						salesPrice: 0,
						stock: 0,
						secondRate: 0,
						firstRate: 0,
					};
				}
			}
		};
		/**
		 * 查询spu绑定的规格
		 */
		const getGoodsSpuSpecsList = (id: string) => {
			getGoodsSpuSpecs({ spuId: id }).then((response) => {
				let spuSpecList = response.data.data;
				if (spuSpecList && spuSpecList.length > 0) {
					spuSpecList[0].goodsSkuSpecsValues.forEach((item: any) => {
						item.picUrls = [item.picUrl];
					});
				}
				data.goodsSpuSpecs = spuSpecList;
			});
		};
		/**
		 * 多规格组件回调事件
		 */
		const getGoodsSkus = (skus: any, goodsSpuSpecs: any) => {
			data.form.goodsSkus = skus;
			data.form.goodsSpuSpecs = goodsSpuSpecs;
		};
		const initForm = () => {
			const { id }: any = $useRoute.query;
			data.goodsSpuSpecs = [];
			getFreightTemplate();
			getCategory();
			if (id) {
				loading.value = true;
				// 修改
				getById(id)
					.then((response) => {
						loading.value = false;
						data.form = response.data.data;
						data.form.categoryIds = [response.data.data.categoryFirstId, response.data.data.categorySecondId];
						if (response.data.data.enableSpecs == '1') {
							getSpecs();
						} else {
							data.form.sku = response.data.data.goodsSkus[0] ? response.data.data.goodsSkus[0] : {};
						}
						getGoodsSpuSpecsList(response.data.data.id);
					})
					.catch(() => {
						loading.value = false;
					});
			}
		};
		initForm();
		return {
			loading,
			formRef,
			fullscreen,
			defaultProps,
			wangEditorRef,
			getSpecs,
			submitForm,
			getCategory,
			handleClose,
			getGoodsSkus,
			changeCategory,
			changeEnableSpecs,
			getFreightTemplate,
			getGoodsSpuSpecsList,
			...toRefs(data),
		};
	},
});
</script>
<style lang="scss">
.goods-footer {
	bottom: 0px;
	width: 100%;
	padding: 10px;
	border-top: 1px solid #ccc;
	background: #fff;

	.el-button {
		width: 200px;
	}

	.button {
		display: flex;
		align-items: center;
		justify-content: center;
	}
}
</style>
